package com.bdk.middle.management.common.exception;

import com.bdk.middle.common.result.ResultDO;
import com.bdk.middle.common.result.web.ObjectResponse;
import com.bdk.middle.common.status.ErrorCode;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    /**
     * 定义要捕获的异常 可以多个 @ExceptionHandler({})
     *
     * @param e        exception
     * @param response response
     * @return 响应结果
     */
    @ExceptionHandler(CustomException.class)
    public ObjectResponse customExceptionHandler(final CustomException e, HttpServletResponse response) {
        ObjectResponse objectResponse = new ObjectResponse();
        objectResponse.setStatus(e.getCode());
        objectResponse.setMsg(e.getMessage());
        return objectResponse;
    }

    /**
     * 定义要捕获的异常 可以多个 @ExceptionHandler({})
     *
     * @param e        exception
     * @param response response
     * @return 响应结果
     */
    @ExceptionHandler(Exception.class)
    public ResultDO ExceptionHandler(final Exception e, HttpServletResponse response) {
        e.printStackTrace();
        ResultDO result = new ResultDO();
        result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
        return result;
    }

    /**
     * 捕获  RuntimeException 异常
     *
     * @param e        exception
     * @param response response
     * @return 响应结果
     */
    @ExceptionHandler(RuntimeException.class)
    public ObjectResponse runtimeExceptionHandler(final Exception e, HttpServletResponse response) {
        ObjectResponse objectResponse = new ObjectResponse();
        objectResponse.setStatus(ErrorCode.SYSTEM_EXCEPTION.getCode());
        objectResponse.setMsg(ErrorCode.SYSTEM_EXCEPTION.getMsg());
        return objectResponse;
    }

    /**
     * 通用的接口映射异常处理方
     */
    
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers,
                                                             HttpStatus status, WebRequest request) {
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
